using Engine;
using Engine.Graphics;
using Game;

namespace SCIENEW {
    /// <summary>
    /// 有燃烧切换、四个方向、有模型、提供动力作用的设备都继承自此
    /// </summary>
    public abstract class IlluminableModelDevice : FourDirectionModelDevice {
        public BlockMesh[] m_litBlockMeshesByData = new BlockMesh[4];
        public BoundingBox[][] m_litCollisionBoxesByFace = new BoundingBox[4][];

        public IlluminableModelDevice(string id, string modelPath, string meshName, string litMeshName, bool faceTransparent = false, bool doubleSided = false) : base(
            id,
            modelPath,
            meshName,
            faceTransparent,
            doubleSided
        ) {
            Model model = ContentManager.Get<Model>(modelPath);
            Matrix boneAbsoluteTransform = BlockMesh.GetBoneAbsoluteTransform(model.FindMesh(litMeshName).ParentBone);
            for (int i = 0; i < 4; i++)
            {
                m_litBlockMeshesByData[i] = new BlockMesh();
                Matrix identity = Matrix.Identity;
                identity *= Matrix.CreateRotationY(i * (float)Math.PI / 2f) * Matrix.CreateTranslation(0.5f, 0f, 0.5f);
                m_litBlockMeshesByData[i].AppendModelMeshPart(model.FindMesh(litMeshName).MeshParts[0], boneAbsoluteTransform * identity, makeEmissive: false, flipWindingOrder: false, doubleSided: doubleSided, flipNormals: false, Color.White);
                m_litCollisionBoxesByFace[i] = [m_litBlockMeshesByData[i].CalculateBoundingBox()];
            }
        }

        protected static bool IsLight(int value) => DevicesUtils.GetInnerData(value) >> 2 == 1;

        public override int GetEmittedLightAmount(int value) => IsLight(value) ? 15 : 0;

        public override float GetHeat(int value) => IsLight(value) ? 0.66f : 0;

        public override int GetShadowStrength(int value) => IsLight(value) ? -99 : base.GetShadowStrength(value);

        public override bool IsTransparent_(int value) => IsLight(value);

        public override void GenerateTerrainVertices(BlockGeometryGenerator generator, TerrainGeometry geometry, int value, int x, int y, int z) {
            generator.GenerateShadedMeshVertices(
                BlocksManager.Blocks[BaseDeviceBlock.Index],
                x,
                y,
                z,
                IsLight(value) ? m_litBlockMeshesByData[GetDirection(value)] : m_blockMeshesByData[GetDirection(value)],
                Color.White,
                null,
                null,
                geometry.GetGeometry(IndustrialModLoader.IETexture).SubsetAlphaTest
            );
        }

        public override BoundingBox[] GetCustomCollisionBoxes(SubsystemTerrain terrain, int value) => IsLight(value) ? m_litCollisionBoxesByFace[GetDirection(value)] : m_collisionBoxesByFace[GetDirection(value)];
    }
}